package net.wy.commons.util;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

/*@Test
public void t(){
	String userTestJson = "{id:1,age:18,sex:true,birthday:'2014-08-05',name:'a',userList:[{id:2,name:'b',userList:[{id:3,name:'c'},{id:4,name:'d'},{id:5,name:'e'}]},{id:6,name:'f'},{id:7,name:'g'}]}";
	UserTest userTest = (UserTest)JsonUtil.toBean(userTestJson, UserTest.class);
	System.out.println(userTest.getBirthday());
}*/

/**
 * JSON转换器
 * @author admin
 */
public class JsonUtil {
	
	/**
	 * 将json对象转成Java对象
	 * @param json
	 * @param obj
	 * @return
	 */
	public static Object toBean(String json, Class<?> obj){
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setRootClass(obj);
		//将数组作为LIST处理
		jsonConfig.setArrayMode(JsonConfig.MODE_LIST);
		//处理日期类型的域
		jsonConfig.setJavaPropertyFilter(new PropertyFilter() {
			@Override
			public boolean apply(Object source, String name, Object value) {
				try {
					Field field = source.getClass().getDeclaredField(name);
					if (field.getType() == Date.class) {
						if(value instanceof String){
							String formats[] = {"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"};
							for( String format : formats ){
								source.getClass().getMethod("set"+name.substring(0, 1).toUpperCase()+name.substring(1), Date.class).invoke(source, DateUtil.getDateFormat((String)value, format));
							}
						}else if(value instanceof Integer){
							source.getClass().getMethod("set"+name.substring(0, 1).toUpperCase()+name.substring(1), Date.class).invoke(source, new Date((Integer)value*1000));
						}
						return true;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return false;
			}
		});
		Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
		Field[] fields = obj.getDeclaredFields();
		for (Field field : fields) {
			Class<?> type = field.getType();
			if (!JsonUtil.isBaseType(type)) {
				if ("java.util.List".equals(type.getName())) {
					classMap.put(field.getName(), (Class<?>)((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]);
				}else{
					classMap.put(field.getName(), type);
				}
			}
		}
		//建立复杂域的映射关系
		jsonConfig.setClassMap(classMap);
		JSONObject jsonObject = JSONObject.fromObject(json);
		return JSONObject.toBean(jsonObject, jsonConfig);
	}
	
	/**
	 * 去掉不用加进classMap的类型
	 * @param type
	 * @return
	 */
	private static boolean isBaseType(Class<?> type){
		if (type == Byte.TYPE || "java.lang.Byte".equals(type.getName())){
			return true;
		}else if (type == Short.TYPE || "java.lang.Short".equals(type.getName())){
			return true;
		}else if (type == Integer.TYPE || "java.lang.Integer".equals(type.getName())){
			return true;
		}else if (type == Long.TYPE || "java.lang.Long".equals(type.getName())) {
			return true;
		}else if (type == Float.TYPE || "java.lang.Float".equals(type.getName())) {
			return true;
		}else if (type == Double.TYPE || "java.lang.Double".equals(type.getName())) {
			return true;
		}else if (type == Boolean.TYPE || "java.lang.Boolean".equals(type.getName())) {
			return true;
		}else if (type == Character.TYPE || "java.lang.Character".equals(type.getName())) {
			return true;
		}else if (type == String.class) {
			return true;
		}else if (type == Date.class) {
			return true;
		}else {
			return false;
		}
	}
	
}
